package com.king.im.handler.impl;

import cn.hutool.json.JSONUtil;
import com.king.common.lang.Consts;
import com.king.im.handler.IMMsgHanlder;
import com.king.im.handler.filter.ExChannelContextFilter;
import com.king.im.message.ChatInMessage;
import com.king.im.message.ChatOutMessage;
import com.king.im.vo.IMMessage;
import com.king.im.vo.IMTo;
import com.king.im.vo.IMUser;
import com.king.service.ChatService;
import com.king.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;

import java.util.Date;

/**
 * 聊天处理器
 */
@Slf4j
public class ChatMsgHanlder implements IMMsgHanlder {
    @Override
    public void handle(String data, WsRequest wsRequest, ChannelContext channelContext) {
        ChatInMessage chatInMessage = JSONUtil.toBean(data, ChatInMessage.class);
        IMUser mine = chatInMessage.getMine();
        IMTo to = chatInMessage.getTo();

        // 特殊处理？ 如过滤非法字符

        IMMessage imMsg = new IMMessage();
        imMsg.setContent(mine.getContent());
        imMsg.setAvatar(mine.getAvatar());
        imMsg.setMine(false);//是否我发送的消息
        imMsg.setUsername(mine.getUsername());

        imMsg.setId(Consts.IM_DEFAULT_GROUP_ID);
        imMsg.setFromid(mine.getId());
        imMsg.setTimestamp(new Date());
        imMsg.setType(to.getType());

        ChatOutMessage chatOutMessage = new ChatOutMessage();
        chatOutMessage.setEmit("chatMessage");
        chatOutMessage.setData(imMsg);

        String chatMsg = JSONUtil.toJsonStr(chatOutMessage);
        log.info("群聊消息 ---------> {}", chatMsg);

        WsResponse wsResponse = WsResponse.fromText(chatMsg, "utf-8");

        ExChannelContextFilter filter = new ExChannelContextFilter();
        filter.setCurrentContext(channelContext);

        Tio.sendToGroup(channelContext.getGroupContext(), Consts.IM_DEFAULT_GROUP_NAME, wsResponse, filter);

        ChatService chatService = (ChatService) SpringUtil.getBean("chatService");
        chatService.setGroupHistoryMsg(imMsg);//保存群聊信息到redis
    }
}
